package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao ;
    @Autowired
    private RoleDao roleDao ;
    @Autowired
    private PermissionDao permissionDao;

    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if(user == null){
            return null;
        }
        Integer userId = user.getId();
        Set<Role> roles = roleDao.findByUserId(userId);
        if(roles !=null && roles.size()>0){
            for (Role role : roles) {
                Integer roleId = role.getId();
                Set<Permission> permissions =  permissionDao.findByRoleId(roleId);

            if(permissions != null && permissions.size() >0 ){
                role.setPermissions(permissions);
            }
            }
            user.setRoles(roles);
        }

        return user;
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        /**
         *
         public List<Integer> findCheckItemIdsByCheckGroupId(Integer id) {
         return checkGroupDao.findCheckItemIdsByCheckGroupId(id);
         }
         */

        return userDao.findRoleIdsByUserId(id);
    }

    @Override
    public void edit(Integer[] roleIds, User user) {
        //清除当前用户和角色关系
        userDao.deleteAssociation(user.getId());
        //重新建立关系
        setUserAndRole(roleIds,user.getId());
        //修改基本信息
        userDao.edit(user);
        }



    @Override
    public List<Role> findAll() {

        return userDao.findRoleAll();


    }


    public void add(Integer[] roleIds, User user) {


        //添加用户，同时需要关联角色信息(操作中间关系表）

        userDao.add(user);
        setUserAndRole(roleIds,user.getId());


    }

    private void setUserAndRole(Integer[] roleIds, Integer userId) {


        //设置用户和角色的关联关系
        if(roleIds != null && roleIds.length > 0){
            for (Integer roleId : roleIds) {
                Map map = new HashMap();
                map.put("userId",userId);
                map.put("roleId",roleId);
                userDao.setUserAndRole(map);
            }
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //分页
        //开始分页---设置分页条件
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<User> page = userDao.selectByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }



    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List<Role> findRoleAll() {
        return userDao.findRoleAll();

    }

    @Override
    public void deleteById(Integer id) {
        /**
         *  //查询当前检查项是否已经关联到检查组
         long count = checkItemDao.findCountByCheckItemId(id);
         if(count > 0){
         //已经被关联，不能删除
         throw new RuntimeException(MessageConstant.CHECKITEMHASASSOCIATION);
         }
         //未被关联，可以删除
         */

        //查询当前检查项是否已经关联到检查组
//        long count = userDao.findCountByUser(id);
//        if(count > 0){
//            //已经被关联，不能删除
////            throw new RuntimeException(MessageConstant.CHECKITEMHASASSOCIATION);
//        }
        //未被关联，可以删除
        userDao.deleteAssociation(id);
        userDao.deleteById(id);

    }



    @Override
    public LinkedHashSet<Menu> getMenu(String username) {
        User user = userDao.findByUsername(username);
        Set<Role> roles1 = user.getRoles();
        if (roles1!=null&&roles1.size()>0){
            for (Role role : roles1) {
                LinkedHashSet<Menu> menus = role.getMenus();
                if (menus!=null&&menus.size()>0){
                    for (Menu menu : menus) {
                        Integer menuId = menu.getId();
                        Integer roleId = role.getId();
                        Map map=new HashMap();
                        map.put("roleId",roleId);
                        map.put("menuId",menuId);
                        List<Menu> children=userDao.findChildrenByMenuId(map);
                        menu.setChildren(children);
                    }
                }
            }
        }
        if (user!=null){

            Set<Role> roles = user.getRoles();
            if (roles!=null&&roles.size()>0){
                for (Role role : roles) {

                    LinkedHashSet<Menu> menus = role.getMenus();
                    if (menus!=null&&menus.size()>0){
                        return menus;
                    }
                }
            }
        }
        return null;
    }
}
